<?php 


function _gc_attributes_alter_group_edition_form(&$form) {
  $form['filters_selection']['product_attributes'] = array(
    '#type' => 'fieldset',
    '#title' => t('Product Attributes Filters'),
    '#weight' => 5,
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
    '#description' => t('You may choose to filter by attributes added to this product'),
  );
  $form['filters_selection']['product_attributes']['attributes'] = _get_attributes_gc_filters_selection_form($form['nid']['#value']);
  $form['#submit'][] = '_gc_attributes_group_edition_form_submit';
}


function _get_attributes_gc_filters_selection_form($gnid) {
  $form = array();
  $attributes = _gc_get_uc_attributes();
  $standard_filters_applied = _get_gc_group_attributes_filters($gnid);
  
  if (is_array($attributes)) {
    foreach($attributes as $attribute) {
      $form[$attribute['aid']] = array(
        '#type' => 'checkbox',
        '#title' => t('Filter by %attribute_name', array('%attribute_name' => $attribute['name'])),
        '#default_value' => $standard_filters_applied[$attribute['aid']]
      ); 
    }
  }

  return $form;
}

function _gc_attributes_group_edition_form_submit(&$form, &$from_state) {
  $attributes = $form['filters_selection']['product_attributes']['attributes'];
  $gnid = $form['nid']['#value'];
  db_query("DELETE FROM {gc_attributes_filters} WHERE gnid=%d", $gnid);
  foreach($attributes as $key => $attribute) {  
    if ($attribute['#value']) {
      db_query("INSERT INTO {gc_attributes_filters} VALUES (%d,%d)",
              $gnid,  $key);  
      }
  }
}

function _gc_get_uc_attributes() {
  $attributes = array();
  $sql = db_query("SELECT aid, name, label FROM {uc_attributes}");
  while($res = db_fetch_object($sql)) {
    $attributes[] = array(
        'aid'  => $res->aid,
        'name' => $res->name,
        'label'=> $res->label
    );
  }
  return $attributes;
}

function _get_gc_group_attributes_filters($gnid) {
  $sql = db_query("SELECT aid FROM {gc_attributes_filters} WHERE gnid=%d",$gnid);
  $filters_applied = array();
  
  while($res = db_fetch_object($sql)) {
    $filters_applied[$res->aid] = 1;
  }
  
  return $filters_applied;
}